<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>私信示例</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/+esm"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        #login-box {
            margin-bottom: 20px;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 8px;
        }

        #message-container {
            height: 500px;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 20px;
            overflow-y: auto;
            border-radius: 8px;
        }

        .message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 15px;
            max-width: 70%;
        }

        .received {
            background: #e9ecef;
            margin-right: auto;
        }

        .sent {
            background: #007bff;
            color: white;
            margin-left: auto;
        }

        #input-box {
            display: flex;
            gap: 10px;
        }

        #message-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background: #0056b3;
        }

        .status {
            color: #6c757d;
            font-size: 0.9em;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div id="login-box">
    <input type="text" id="userId" placeholder="输入你的用户ID">
    <button onclick="connect()">连接</button>
    <button onclick="disconnect()" style="background: #dc3545">断开</button>
    <div class="status" id="connection-status">未连接</div>
</div>

<div id="message-container"></div>

<div id="input-box">
    <input type="text" id="message-input" placeholder="输入消息...">
    <input type="text" id="receiverId" placeholder="接收者ID" style="width: 120px">
    <button onclick="sendMessage()">发送</button>
</div>

<script>
    let stompClient = null;
    let currentUserId = null;

    function connect() {
        currentUserId = document.getElementById('userId').value;
        if (!currentUserId) {
            alert('请输入用户ID');
            return;
        }
        console.log(`正在连接（用户ID: ${currentUserId}）`)

        const socket = new SockJS('http://localhost:8089/api/v1/ws?userId=' + currentUserId);
        stompClient = Stomp.over(socket);

        stompClient.connect({}, (frame) => {
            updateStatus(`已连接（用户ID: ${currentUserId}）`);

            // 订阅个人消息队列
            stompClient.subscribe(`/user/queue/messages`, (message) => {
                const msg = JSON.parse(message.body);
                addMessageToScreen(msg, false);
            });

            // 加载历史消息
            fetch(`/messages?userId=${currentUserId}&page=0&size=20`)
                .then(response => response.json())
                .then(messages => {
                    messages.content.forEach(msg => {
                        addMessageToScreen(msg, msg.senderId == currentUserId);
                    });
                });
        }, (error) => {
            console.error('连接失败:', error);
            updateStatus('连接失败');
        });
    }

    function disconnect() {
        if (stompClient !== null) {
            stompClient.disconnect();
            updateStatus('已断开连接');
        }
        currentUserId = null;
    }

    function sendMessage() {
        const receiverId = document.getElementById('receiverId').value;
        const content = document.getElementById('message-input').value;

        if (!receiverId || !content) {
            alert('请填写接收者ID和消息内容');
            return;
        }

        const message = {
            senderId: currentUserId,
            receiverId: receiverId,
            content: content
        };

        stompClient.send("/api/v1/chat/send", {}, JSON.stringify(message));
        document.getElementById('message-input').value = '';
    }

    function addMessageToScreen(message, isSent) {
        const container = document.getElementById('message-container');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isSent ? 'sent' : 'received'}`;

        const time = new Date(message.createdAt).toLocaleTimeString();
        messageDiv.innerHTML = `
                <div style="font-weight: bold">${isSent ? '我' : '用户' + message.senderId}</div>
                <div>${message.content}</div>
                <div style="font-size: 0.8em; margin-top: 5px">${time}</div>
            `;

        container.appendChild(messageDiv);
        container.scrollTop = container.scrollHeight;
    }

    function updateStatus(text) {
        document.getElementById('connection-status').textContent = text;
    }

    // 自动滚动到底部
    function scrollToBottom() {
        const container = document.getElementById('message-container');
        container.scrollTop = container.scrollHeight;
    }
</script>
</body>
</html>